package com.proyecto.core.modelo;

import org.hibernate.CacheMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class HibernateTransaccion {
	TransactionStatus           status        = null;
	HibernateTransactionManager transaccion   = null;
	Session  					sesionAbierta = null;
	
	int tamanoBufferFetch = 500;
	
	public HibernateTransaccion() {
		super();
	}

	public HibernateTransaccion(HibernateTransactionManager transaccion) {
		super();
		this.transaccion = transaccion;
		this.status = this.transaccion.getTransaction(new DefaultTransactionDefinition());
	}
	
	public void iniciarTransaccion(){
		if (this.transaccion != null && this.status == null){
			this.status = this.transaccion.getTransaction(new DefaultTransactionDefinition());
		}
	}

	public void iniciarTransaccion(HibernateTransactionManager transaccion){
		this.transaccion = transaccion;
		if (this.transaccion != null){
			this.status = this.transaccion.getTransaction(new DefaultTransactionDefinition());
		}
	}

	public void finalizarTransaccion(){
		if (this.transaccion.getSessionFactory() != null && 
			this.status != null && !this.status.isCompleted()){
			this.transaccion.commit(this.status);
		}
	}
	
	public void reversarTransaccion(){
		if (this.transaccion != null && 
			this.status != null && !this.status.isCompleted()){
			this.transaccion.rollback(this.status);
		}
	}

	public Session getOpenSession(){
		if (this.transaccion != null){
			return this.getTransaccion().getSessionFactory().openSession();
		}else{
			return null;
		}
	}
	
	public ScrollableResults ejecutarQueryScrollable(String queryString, int tamanoBufferFetch){
		this.tamanoBufferFetch = tamanoBufferFetch;
		this.sesionAbierta = this.getOpenSession();
		ScrollableResults lista = this.getOpenSession().createQuery(queryString).
									setCacheMode(CacheMode.IGNORE).setFetchSize(this.tamanoBufferFetch).scroll(ScrollMode.FORWARD_ONLY);
		return lista;
	}
	
	public boolean recargaBuffer(Integer filaActual){
		boolean recargada = false;
		
		if ( (filaActual % this.tamanoBufferFetch) == 0){
			if (sesionAbierta == null) {
				this.sesionAbierta = this.getOpenSession();
			}
	        //flush a batch of updates and release memory:
			//this.sesionAbierta.flush();
			this.sesionAbierta.clear();
			recargada = true;
	    }
		return recargada;
	}
	
	// M�todos de uso general 
	public HibernateTransactionManager getTransaccion() {
		return transaccion;
	}

	public void setTransaccion(HibernateTransactionManager transaccion) {
		this.transaccion = transaccion;
	}
	
}
